﻿using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using TransformerManager.Shared.Dto.Transformer;
using TransformerManager.Shared.Helper.HttpParams;
using TransformerManager.Shared.ResourceParameters;

namespace TransformerManager.WPF.Common.Http.Service
{
    public class TransformerService : ITransformerService
    {
        private readonly HttpRequest _httpRequest;
        public TransformerService(HttpRequest httpRequest)
        {
            _httpRequest = httpRequest;
        }

        public async Task<ResponseParams> AddTransformerAsync(TransformerDto transformerDto)
        {
            string url = $"Transformers";
            string body = JsonConvert.SerializeObject(transformerDto);
            return await _httpRequest.RequestAsync(HttpMethod.Post, url, null, body);
        }

        public async Task<ResponseParams> CheckProjectNumberValidAsync(string projectNumber)
        {
            string url = $"Transformers/{projectNumber}";
            return await _httpRequest.RequestAsync(HttpMethod.Get, url, null);
        }

        public async Task<ResponseParams> DeleteTransformerByIdAsync(Guid id)
        {
            string url = $"Transformers/{id}";
            // 获取响应
            return await _httpRequest.RequestAsync(HttpMethod.Delete, url, null);
        }

        public async Task<ResponseParams> GetTransformerInfoById(Guid id)
        {
            string url = $"Transformers/{id}";
            // 获取响应
            return await _httpRequest.RequestAsync(HttpMethod.Get, url, null);
        }

        public async Task<ResponseParams> GetTransformersAsync(TransformerResourceParameters transformerResource, int pageIndex, int pageSize)
        {
            string url = $"Transformers/Query?pageNumber={pageIndex}&pageSize={pageSize}";
            string body = JsonConvert.SerializeObject(transformerResource);
            return await _httpRequest.RequestAsync(HttpMethod.Post, url, null, body);
        }

        public async Task<int> GetTransformersNumByRegionAsync(string region, DateTime from, DateTime end)
        {
            string url = $"Transformers/Number?regionType={region}&from={from}&end={end}";

            var responseParams = await _httpRequest.RequestAsync(HttpMethod.Get, url, null);
            if (responseParams == null) return 0;

            return int.Parse(responseParams.Result.ToString());
        }

        public async Task<ResponseParams> UpdateTransformerInfoByIdAsync(Guid Id, TransformerDto transformerDto)
        {
            // 请求数据
            string url = $"Transformers/{Id}";
            string body = JsonConvert.SerializeObject(transformerDto);

            // 获取响应
            return await _httpRequest.RequestAsync(HttpMethod.Put, url, null, body);
        }
    }
}
